<template>
  <!-- 弹出浮窗 -->
  <el-dialog
    title="安全中心"
    v-model="dialogVisible"
    width="50%"
  >
    <el-tabs
      v-model="activeTab"
      type="card"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        label="修改邮箱"
        name="email"
      >
        <!-- 修改邮箱表单 -->
        <el-form
          :model="emailForm"
          ref="formRef"
          :rules="rules"
          label-width="100px"
          @validate="onValidate"
        >
          <el-form-item
            label="新邮箱"
            prop="email"
          >
            <el-input
              v-model="emailForm.email"
              type="email"
              placeholder="请输入新邮箱"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="输入验证码"
            prop="code"
          >
            <el-row
              :gutter="10"
              style="width: 100%"
            >
              <el-col :span="20">
                <el-input
                  v-model="emailForm.code"
                  :maxlength="6"
                  type="code"
                  placeholder="请输入验证码"
                >
                  <template #prefix>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-button
                  type="success"
                  style="width:120px"
                  @click="validateEmail"
                  :disabled="!isEmailValid"
                >
                  {{'获取验证码'}}
                  >
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="saveEmail"
            >保存</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        label="修改密码"
        name="password"
      >
        <!-- 修改密码表单 -->
        <el-form
          :model="passwordForm"
          ref="formRef"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="当前密码">
            <el-input
              v-model="passwordForm.currentPassword"
              placeholder="请输入当前密码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="新密码"
            prop="newPassword"
          >
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="确认密码"
            prop="confirmPassword"
          >
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="savePassword"
            >保存</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script >
import { ref, watch } from 'vue';
import { put, post } from "@/net";
import { ElMessage } from 'element-plus';

export default {
  name: "securitydialog",
  props: {
    modelValue: {
      type: Boolean,
      required: true,
    },
    userinfo: {
      type: Object,
      required: true,
    },
  },
  emits: ['update:modelValue'],
  setup (props, { emit }) {
    const isEmailValid = ref(false)
    const coldTime = ref(0)
    const dialogVisible = ref(props.modelValue);// 浮窗的显示状态
    const activeTab = ref('email');// 当前活动的 tab
    // 邮箱表单数据
    const emailForm = ref({
      email: '',
      code: ''
    });
    // 密码表单数据
    const passwordForm = ref({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    const formRef = ref(null);
    // 监听 props.modelValue 更新 dialogVisible
    watch(() => props.modelValue, (newVal) => {
      dialogVisible.value = newVal;
    });

    // 当 dialogVisible 被修改时，发射更新事件，通知父组件
    watch(dialogVisible, (newVal) => {
      emit('update:modelValue', newVal);
    });
    // 打开浮窗
    const openSecurityDialog = () => {
      dialogVisible.value = true;
    };
    // 关闭浮窗
    const closeDialog = () => {
      dialogVisible.value = false;
      // 使用 resetFields 重置表单
      emailForm.value = ref({
        email: '',
        code: ''
      });
      passwordForm.value = ref({
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
    };
    // 切换 tab 时的操作
    const handleTabClick = (tab) => {
      console.log('当前选择的tab:', tab.name);
    };

    // 保存邮箱
    const saveEmail = () => {
      put('/account/verify_email_code', {
        email: emailForm.value.email,
        code: emailForm.value.code
      }, (message) => {
        ElMessage.success(message.msg);
        put(
          "/account/update_email",
          {
            id: props.userinfo.id,
            email: emailForm.value.email,
          },
          (message) => {
            ElMessage.success(message.msg);
            closeDialog();
          },
          (message) => {
            ElMessage.error(message.msg);
          }
        );
      }, (message) => {
        ElMessage.error(message.msg);
      });

    };
    // 保存密码
    const savePassword = () => {
      put(
        "/account/reset_pwd",
        {
          id: props.userinfo.id,
          currentPassword: passwordForm.value.currentPassword,
          newPassword: passwordForm.value.newPassword
        },
        (message) => {
          ElMessage.success(message.msg);
          closeDialog();
        },
        (message) => {
          ElMessage.error(message.msg);
        }
      );
    };
    const validatePassword = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== passwordForm.value.newPassword) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    };
    const rules = {
      newPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码的长度必须在6-16个字符之间', trigger: ['blur', 'change'] }
      ],
      confirmPassword: [
        { validator: validatePassword, trigger: ['blur', 'change'] },
      ],
      email: [
        { required: true, message: '请输入邮件地址', trigger: 'blur' },
        { type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change'] }
      ],
      code: [
        { required: true, message: '请输入获取的验证码', trigger: 'blur' },
      ]
    };
    const onValidate = (prop, isValid) => {
      if (prop == 'email')
        isEmailValid.value = isValid
    }
    const validateEmail = () => {
      coldTime.value = 60
      post('/account/verify_email', {
        email: emailForm.value.email
      }, (message) => {
        ElMessage.success(message.msg)
        setInterval(() => coldTime.value--, 1000)
      }, (message) => {
        ElMessage.warning(message.msg)
        coldTime.value = 0
      })
    }
    return {
      dialogVisible, activeTab, emailForm, passwordForm, closeDialog,
      handleTabClick, saveEmail, savePassword, openSecurityDialog, rules, isEmailValid, coldTime, onValidate, formRef, validateEmail
    };

  },
}
</script>

  <style scoped>
</style>